<template>
  <div class="movie-crawler">
    <!-- 控制面板 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>电影数据采集</h3>
              <el-button-group>
                <el-button 
                  type="primary" 
                  :loading="crawling" 
                  @click="startCrawler"
                  :disabled="crawling"
                >
                  <el-icon><VideoPlay /></el-icon>
                  开始采集
                </el-button>
                <el-button 
                  type="danger" 
                  :loading="stopping" 
                  @click="stopCrawler"
                  :disabled="!crawling"
                >
                  <el-icon><VideoPause /></el-icon>
                  停止采集
                </el-button>
              </el-button-group>
            </div>
          </template>
          
          <el-alert
            v-if="crawling"
            type="info"
            :closable="false"
            show-icon
          >
            正在采集中，请稍候...
          </el-alert>
          
          <el-alert
            v-if="lastError"
            type="error"
            :closable="true"
            show-icon
            @close="lastError = ''"
            class="mt-3"
          >
            {{ lastError }}
          </el-alert>
        </el-card>
      </el-col>
    </el-row>

    <!-- 状态卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h4>采集状态</h4>
            </div>
          </template>
          <div class="status-content">
            <el-tag :type="crawling ? 'success' : 'info'">
              {{ crawling ? '采集中' : '已停止' }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h4>已采集数量</h4>
            </div>
          </template>
          <div class="status-content">
            <span class="count-number">{{ crawledCount }}</span>
            <span class="count-unit">条</span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="8">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h4>最新采集</h4>
            </div>
          </template>
          <div class="status-content">
            <span class="latest-movie">{{ latestMovie || '暂无数据' }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日志面板 -->
    <el-card class="log-card">
      <template #header>
        <div class="card-header">
          <h4>采集日志</h4>
          <el-button 
            type="primary" 
            link 
            @click="clearLogs"
            :disabled="!logs.length"
          >
            清空日志
          </el-button>
        </div>
      </template>
      <div class="log-content">
        <p 
          v-for="(log, index) in logs" 
          :key="index"
          :class="['log-item', `log-${log.type}`]"
        >
          <span class="log-time">{{ log.time }}</span>
          <span class="log-message">{{ log.message }}</span>
        </p>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.movie-crawler {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 20px;
}

.mt-3 {
  margin-top: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.card-header h4 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.status-content {
  text-align: center;
  padding: 20px 0;
}

.count-number {
  font-size: 24px;
  font-weight: bold;
  color: var(--el-color-primary);
}

.count-unit {
  margin-left: 4px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.latest-movie {
  font-size: 14px;
  color: var(--el-text-color-regular);
}

.log-card {
  margin-top: 20px;
}

.log-content {
  padding: 8px;
  font-size: 12px;
  line-height: 1.2;
}

.log-item {
  margin: 0;
  padding: 4px 0;
  border-bottom: 1px dashed var(--el-border-color-lighter);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.log-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.log-time {
  color: var(--el-text-color-secondary);
  margin-right: 8px;
  font-family: monospace;
}

.log-message {
  color: var(--el-text-color-regular);
}

.log-info {
  color: var(--el-text-color-regular);
}

.log-error {
  color: var(--el-color-danger);
}

.log-success {
  color: var(--el-color-success);
}
</style>

<script setup>
import { ref, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'
import { startCrawler as startCrawlerApi, stopCrawler as stopCrawlerApi, getCrawlerStatus } from '@/api/movie'

// 状态变量
const crawling = ref(false)
const stopping = ref(false)
const crawledCount = ref(0)
const lastError = ref('')
const logs = ref([])
const latestMovie = ref('')

// 开始爬虫
const startCrawler = async () => {
  try {
    if (crawling.value) {
      ElMessage.warning('爬虫已在运行中')
      return
    }
    
    crawling.value = true
    lastError.value = ''
    addLog('info', '正在启动爬虫...')
    
    const response = await startCrawlerApi()
    console.log('爬虫启动响应:', response)  // 调试日志
    
    // 检查响应状态
    if (response?.status === 'success' || response?.data?.status === 'success') {
      const message = response.message || response.data?.message || '爬虫启动成功'
      ElMessage.success(message)
      addLog('info', message)
      
      // 更新状态
      const data = response.data?.data || response.data || {}
      crawledCount.value = data.count || 0
      latestMovie.value = data.latest_movie || ''
      
      // 添加详细状态日志
      addLog('info', `当前状态: ${JSON.stringify(data)}`)
      
      // 开始轮询爬虫状态
      pollCrawlerStatus()
    } else {
      const errorMsg = response?.message || response?.data?.message || '爬虫启动失败'
      console.error('爬虫启动失败:', response)  // 错误日志
      throw new Error(errorMsg)
    }
  } catch (error) {
    console.error('启动爬虫失败:', error)
    // 获取详细的错误信息
    let errorMessage = '启动爬虫失败'
    if (error.response?.data?.message) {
      errorMessage = error.response.data.message
    } else if (error.message) {
      errorMessage = error.message
    }
    
    // 如果有详细的错误堆栈，也记录下来
    if (error.stack) {
      console.error('错误堆栈:', error.stack)
      addLog('error', `错误详情: ${error.stack}`)
    }
    
    lastError.value = errorMessage
    addLog('error', `启动失败: ${errorMessage}`)
    crawling.value = false
    ElMessage.error(errorMessage)
  }
}

// 停止爬虫
const stopCrawler = async () => {
  try {
    stopping.value = true
    const response = await stopCrawlerApi()
    
    if (response && response.data && response.data.status === 'success') {
      ElMessage.success('爬虫已停止')
      addLog('info', '爬虫已停止')
      crawling.value = false
    } else {
      const errorMsg = response?.data?.message || '停止爬虫失败'
      throw new Error(errorMsg)
    }
  } catch (error) {
    console.error('停止爬虫失败:', error)
    lastError.value = error.message || '停止爬虫失败'
    addLog('error', `停止失败: ${lastError.value}`)
    ElMessage.error(lastError.value)
  } finally {
    stopping.value = false
  }
}

// 轮询爬虫状态
let statusTimer = null
const pollCrawlerStatus = async () => {
  if (statusTimer) {
    clearInterval(statusTimer)
  }
  
  statusTimer = setInterval(async () => {
    try {
      const response = await getCrawlerStatus()
      console.log('爬虫状态:', response)  // 调试日志
      
      if (response?.status === 'success' || response?.data?.status === 'success') {
        const data = response.data?.data || response.data || {}
        const { count, is_running, latest_movie, error } = data
        
        // 添加详细状态日志
        addLog('info', `状态更新: ${JSON.stringify(data)}`)
        
        // 更新计数
        if (typeof count === 'number') {
          crawledCount.value = count
        }
        
        // 更新最新电影
        if (latest_movie && latest_movie !== latestMovie.value) {
          latestMovie.value = latest_movie
          addLog('info', `采集电影: ${latest_movie}`)
        }
        
        // 处理错误
        if (error) {
          lastError.value = error
          addLog('error', error)
          console.error('爬虫错误:', error)  // 错误日志
          ElMessage.error(error)
          clearInterval(statusTimer)
          crawling.value = false
          return
        }
        
        // 检查是否完成
        if (!is_running) {
          clearInterval(statusTimer)
          crawling.value = false
          if (count > 0) {
            const successMsg = `采集完成，共获取 ${count} 部电影`
            addLog('success', successMsg)
            ElMessage.success(successMsg)
          } else {
            const msg = '采集完成，但未获取到数据'
            addLog('error', msg)
            console.warn('爬虫未获取到数据')  // 警告日志
            ElMessage.warning(msg)
          }
        }
      } else {
        const errorMsg = response?.message || response?.data?.message || '获取爬虫状态失败'
        console.error('获取状态失败:', response)  // 错误日志
        throw new Error(errorMsg)
      }
    } catch (error) {
      console.error('获取爬虫状态失败:', error)
      // 获取详细的错误信息
      let errorMessage = '获取爬虫状态失败'
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message
      } else if (error.message) {
        errorMessage = error.message
      }
      
      clearInterval(statusTimer)
      lastError.value = errorMessage
      crawling.value = false
      addLog('error', `状态获取失败: ${errorMessage}`)
      ElMessage.error(errorMessage)
    }
  }, 3000)
}

// 添加日志
const addLog = (type, message) => {
  const now = new Date()
  const time = now.toLocaleTimeString()
  logs.value.unshift({ type, message, time })
  
  // 最多保留100条日志
  if (logs.value.length > 100) {
    logs.value = logs.value.slice(0, 100)
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 组件销毁时清理定时器
onUnmounted(() => {
  if (statusTimer) {
    clearInterval(statusTimer)
  }
})
</script> 